/**
 * Created by peng on 2015/5/14.
 */

var urlroot = "http://60.2.176.70:9889/";
var pleasewait = $('#pleaseWaitDialog');

$(document).ready(function () {

    var job_date = new Date().yyyymmdd();

    $("#userLogin").click(function () {
        var user_id = $("#user_id").val();
        writeCookie("user_id", user_id, 99);
        $("#loginModal").modal('hide');
        load_today_jobs_not_sent();
    });

    var user_id = readCookie("user_id");

    if (user_id == null || user_id == '') {
        $("#loginModal").modal('show');
    }

    $('#btn_settings_save').click(function(){
        var user_id = readCookie('user_id');

        var user_name = $('#user_name').val();
        var user_mail =  $('#user_mail').val();
        var mail_pwd = $('#mail_pwd').val();
        var mail2 = $('#mail2').val();
        var user_depart = $('#user_depart').val();
        var prefix_flag = $('#prefix_flag').val();


        var json_obj = {
            id:user_id, name:user_name, mail:user_mail,mailpwd:mail_pwd, mail2:mail2, depart:user_depart, prefix_depart:prefix_flag
        };

        var post_url = urlroot + 'users';


        $.ajax({type:'POST', data:json_obj, url:post_url, success:function(data){

            $('#settingsModal').modal('hide');

            console.log(data);

            alert('用户信息已保存!');

        }});

    });

    load_user_info(user_id);


});

function load_today_jobs_not_sent() {

    var url = urlroot + "jobs/nobuild/" + readCookie('user_id') + '/' + new Date().yyyymmdd();

    $('#today-list > tr').remove();

    var table = document.getElementById('today-list');
    $.getJSON(url, function (data) {
        for (var i = 0; i < data.length; i++) {

            var row = table.insertRow(0);
            var id = data[i]['_id'];
            row.id = id;
            $("#" + id).hover(function () {
                $(this).toggleClass("hover")
            });

            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            var cell3 = row.insertCell(2);
            var cell4 = row.insertCell(3);
            var cell5 = row.insertCell(4);

            cell1.innerHTML = '<input type="checkbox" onclick="set_remove_btn_status()">';
            cell2.innerHTML = data[i]['title'];
            cell3.innerHTML = data[i]['description'];
            cell4.innerHTML = '<button type="button" class="btn btn-xs pull-right" onclick="edit_project_info(' + "'" + id + "'" + ')">Edit</button>';
            cell5.innerHTML = '<button type="button" class="btn btn-xs pull-left" onclick="remove_project_info(' + "'" + id + "'" + ')">Remove</button>';
        }
    });
}

function remove_project_infl_by_selected(){

    $('#batch_remove').prop('disabled',true);

    $('tbody :checked').each(function(){
        var id = $(this).parent().parent().attr('id');
        remove_project_info(id);
    })
}

function set_remove_btn_status(){
    $('#batch_remove').prop('disabled', !$('tbody :checked').length);
}

function load_user_info(user_id){
    var get_url = urlroot + 'users/userid/' + user_id;

    console.log(get_url);

    $.ajax({type:'GET', url:get_url, success:function(data){

        $('#user_name').val(data['name']);
        $('#user_mail').val(data['mail']);
        $('#mail_pwd').val(data['mailpwd']);
        $('#mail2').val(data['mail2']);
        $('#user_depart').val(data['depart']);
        $('#prefix_flag').val(data['prefix_depart']);

    }, error:function(err){
        console.log(typeof err)

    } });
}

function hideEditModal(){
    $('#projectName').val('');$('#projectDescription').val('');$('#editModal').modal('hide');
}

function send(){

    showPleaseWait();

    var urlpost = urlroot + 'excel';
    var json_obj = {
        "user_id": readCookie('user_id'),
        "date": new Date().yyyymmdd()
    };

    $.ajax({type:'POST', url:urlpost, data:json_obj ,success:function(data){
        $('tbody > tr').each(function(){
            var id = $(this).attr('id');
            remove_project_info(id);
        })
        hidePleaseWait();
    }});
}

function remove_project_info(id) {
    $("#" + id).fadeOut(function () {
        var post_url = urlroot + 'jobs/' + id;
        $.ajax({
            type: 'DELETE', url: post_url, success: function (data) {
                $("#" + id).remove();
            }
        });
    });
}

function edit_project_info(id) {
    var t = $("#" + id).find("td");
    var title = t.eq(1).text();
    var desc = t.eq(2).text();
    $("#projectName").val(title);
    $("#projectDescription").val(desc);

    $("#project_save").data("current_id", id);
    $("#editModal").modal("show");
}

function save_project_info() {
    var title = $("#projectName").val();
    var desc = $("#projectDescription").val();
    var done_status = '0';
    var user_id = readCookie('user_id');
    var job_date = new Date().yyyymmdd();

    var json_obj = {
        "title": title,
        "description": desc,
        "done_status": done_status,
        "user_id": user_id,
        "date": job_date
    };

    var opt_type = 'POST';
    var post_url = urlroot + 'jobs';

    var current_id = $("#project_save").data("current_id");

    if (typeof current_id == 'string') {
        opt_type = 'PUT';
        post_url = urlroot + 'jobs/' + current_id;
    }

    $.ajax({
        type: opt_type,
        url: post_url,
        data: json_obj,
        success: function (data) {
            $("#editModal").modal('hide');
            var id = data['_id'];
            var line = $("#" + id);
            if (line.length) {
                line.find("td").eq(0).html('<input type="checkbox" onclick="set_remove_btn_status()">');
                line.find("td").eq(1).html(data['title']);
                line.find("td").eq(2).html(data['description']);
                line.find("td").eq(3).html('<button type="button" class="btn btn-xs pull-right" onclick="edit_project_info(' + "'" + id + "'" + ')">Edit</button>');
                line.find("td").eq(4).html('<button type="button" class="btn btn-xs pull-left" onclick="remove_project_info(' + "'" + id + "'" + ')">Remove</button>');
                $("#project_save").removeData("current_id");
            }
            else {
                var table = document.getElementById('today-list');
                var row = table.insertRow(0);

                row.id = id;
                $("#" + id).hover(function () {
                    $(this).toggleClass("hover")
                });

                var cell1 = row.insertCell(0);
                var cell2 = row.insertCell(1);
                var cell3 = row.insertCell(2);
                var cell4 = row.insertCell(3);
                var cell5 = row.insertCell(4);

                cell1.innerHTML = '<input type="checkbox" onclick="set_remove_btn_status()">';
                cell2.innerHTML = data['title'];
                cell3.innerHTML = data['description'];
                cell4.innerHTML = '<button type="button" class="btn btn-xs pull-right" onclick="edit_project_info(' + "'" + id + "'" + ')">Edit</button>';
                cell5.innerHTML = '<button type="button" class="btn btn-xs pull-left" onclick="remove_project_info(' + "'" + id + "'" + ')">Remove</button>';
            }

            $("#projectName").val('');
            $("#projectDescription").val('');

        }
    });
}

function switch_table(){
    if (!$('#main_table').is(':hidden')){
        $('#switch_table').text('Today');
        $('#main_table').hide();
        $('#main_btn_group').hide();
        $('#history_table').show('1000');
        load_history_jobs();
    }else{
        $('#switch_table').text('History');
        $('#main_btn_group').show('1000');
        $('#main_table').show('1000');
        $('#history_table').hide();
        load_today_jobs_not_sent();
    }
}

function load_history_jobs(){

    $('#history-list > tr').remove();

    var table = document.getElementById('history-list');

    var url = urlroot + 'excelfile/' + readCookie('user_id') + '/sent';

    $.getJSON(url, function(data){

        for (var i=0; i<data.length;i++){

            var row = table.insertRow(0);
            var id = data[i]['_id'];
            row.id = id;
            $('#' + id).hover(function(){
                $(this).toggleClass('hover');
            });

            var c1 = row.insertCell(0);
            var c2 = row.insertCell(1);
            var c3 = row.insertCell(2);
            var c4 = row.insertCell(3);

            c1.innerHTML = data[i]['date'];

            var filename = data[i]['filepath'];

            filename=filename.substr(filename.lastIndexOf('\\')+1);


            var url = urlroot + 'excelfile/download/' + id;
            c2.innerHTML = '<a href="'+url+'">'+filename+'</a>';
            c3.innerHTML = data[i]['sent']=='1'? '是':'否';
            c4.innerHTML = '<button type="button" class="btn btn-xs pull-left" onclick="view_history_detail(' + "'" + data[i]['date'] + "'" + ')">Detail</button>';
        }


    });
}


function view_history_detail(date){

    $.getJSON(urlroot + 'jobs/build/' + readCookie('user_id') + '/' + date,
    function(data){
        $('#history_detail > tr').remove();
        var table = document.getElementById('history_detail');
        for (var i=0; i<data.length; i++){
            var row = table.insertRow();
            var c1 = row.insertCell(0);
            var c2 = row.insertCell(1);
            c1.innerHTML = data[i]['title'];
            c2.innerHTML = data[i]['description'];
        }
        $('#historyDetailModal').modal('show');
    });

}

function writeCookie(name, value, days) {
    var date, expires;
    if (days) {
        date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var i, c, ca, nameEQ = name + "=";
    ca = document.cookie.split(';');
    for (i = 0; i < ca.length; i++) {
        c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return '';
}

Date.prototype.yyyymmdd = function () {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
    var dd = this.getDate().toString();
    return yyyy + '-' + (mm[1] ? mm : "0" + mm[0]) + '-' + (dd[1] ? dd : "0" + dd[0]); // padding
}

function showPleaseWait(){
    pleasewait.modal('show');
}

function hidePleaseWait(){
    pleasewait.modal('hide');
}
